package Services

import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Middlewares"
)

func addData(title string, url string, start_date string, end_date string) bool {
	tx, err1 := Databases.Db.Begin()
	if err1 != nil {
		if tx != nil {
			_ = tx.Rollback()
		}
		fmt.Printf("begin trans action failed, err:%v\n", err1)
		return false
	}
	sql := "insert into macro_continuous_data (Fstart_date,Fend_date,Ftitle,Furl,Fstatus,Fcreate_time,Fmodify_time) values (?,?,?,?,1,now(),now());"
	fmt.Printf("sql,", sql)
	_,err := Databases.Db.Exec(sql, start_date, end_date, title, url)
	if err != nil {
		tx.Rollback()
		fmt.Println("insert failed, ", err)
		return false
	}

	start_sql := "insert into macro_data_temp (Fdate,Ftype,Ftitle,Furl,Fsite,Fstatus,Fcreate_time,Fmodify_time) values (?,0,?,?,'',0,now(),now());"
	fmt.Printf("sql,", start_sql)
	_,err3 := Databases.Db.Exec(start_sql, start_date, title + "[开始]", url)
	if err3 != nil {
		tx.Rollback()
		fmt.Println("insert failed, ", err3)
		return false
	}

	end_sql := "insert into macro_data_temp (Fdate,Ftype,Ftitle,Furl,Fsite,Fstatus,Fcreate_time,Fmodify_time) values (?,0,?,?,'',0,now(),now());"
	fmt.Printf("sql,", end_sql)
	_,err2 := Databases.Db.Exec(end_sql, end_date, title + "[结束]", url)
	if err2 != nil {
		tx.Rollback()
		fmt.Println("insert failed, ", err2)
		return false
	}

	tx.Commit()
	return true
}

// 宏观数据
func ContinuousOverallDataAdd(c *gin.Context) {
	if (!Middlewares.CheckLogin(c)) {
		c.JSON(http.StatusOK, gin.H{
	        "result": -1,
	        "msg":    "login fail",
	        "data": "{}",
	    })
	    return
	}

	title := c.Query("title")
	url := c.Query("url")
	start_date := c.Query("start_date")
	end_date := c.Query("end_date")
	
	if (!addData(title, url, start_date, end_date)) {
		c.JSON(http.StatusOK, gin.H{
	        "result": -2,
	        "msg":    "insert fail",
	        "data": "",
	    })
		return;
	}

	
    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": "",
    })
}

